package v1

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"gopkg.in/yaml.v2"

)

func Of(file string) (*Resource, error) {
	var err error
	if _, err = os.Stat(file); err != nil {
		return nil, errors.New(fmt.Sprintf("file:%s not found", file))
	}
	fileAbsPath, err := filepath.Abs(file)

	if err != nil {
		return nil, err
	}

	data, err := ioutil.ReadFile(fileAbsPath)
	if err != nil {
		return nil, err
	}
	res := &Resource{Content: string(data)}

	if err = yaml.Unmarshal(data, res); err != nil {
		return nil, err
	}
	if res.Metadata.Namespace == "" {
		res.Metadata.Namespace = "default"
	}
	return res, nil
}
